<template>
  <view class="page-container">
    <scroll-view scroll-y class="detail-scroll" v-if="bookingData.id">
      <!-- 预订状态卡片 -->
      <view class="status-card">
        <view class="status-header">
          <view class="status-info">
            <uni-tag 
              :text="getStatusText(bookingData.status || 1)" 
              :type="getStatusType(bookingData.status || 1)" 
              size="normal"
            />
            <text class="booking-id">#{{ bookingData.id }}</text>
          </view>
          <view class="status-actions">
            <button 
              v-if="bookingData.status === 1" 
              class="action-btn confirm" 
              @click="confirmBooking"
            >
              确认预订
            </button>
            <button 
              v-if="bookingData.status === 1" 
              class="action-btn cancel" 
              @click="cancelBooking"
            >
              取消预订
            </button>
            <button 
              v-if="bookingData.status === 2" 
              class="action-btn start" 
              @click="startBooking"
            >
              开始使用
            </button>
            <button 
              v-if="bookingData.status === 3" 
              class="action-btn finish" 
              @click="finishBooking"
            >
              结束使用
            </button>
          </view>
        </view>
      </view>

      <!-- 预订信息 -->
      <uni-card title="预订信息" :is-shadow="true">
        <view class="info-section">
          <view class="info-row">
            <text class="info-label">场地名称</text>
            <text class="info-value">{{ bookingData.venue_name || '' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">预订日期</text>
            <text class="info-value">{{ formatDate(bookingData.booking_date || '') }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">使用时间</text>
            <text class="info-value">
              {{ bookingData.start_time }} - {{ bookingData.end_time }}
              ({{ Math.floor((bookingData.duration || 0) / 60) }}小时{{ (bookingData.duration || 0) % 60 }}分钟)
            </text>
          </view>
          <view class="info-row">
            <text class="info-label">预订类型</text>
            <text class="info-value">{{ getBookingTypeText(bookingData.booking_type || 1) }}</text>
          </view>
        </view>
      </uni-card>

      <!-- 客户信息 -->
      <uni-card title="客户信息" :is-shadow="true">
        <view class="info-section">
          <view class="info-row">
            <text class="info-label">客户姓名</text>
            <text class="info-value">{{ bookingData.customer_name || '' }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">联系电话</text>
            <view class="info-value-with-action">
              <text class="info-value">{{ bookingData.customer_phone || '' }}</text>
              <button class="call-btn" @click="makeCall" v-if="bookingData.customer_phone">
                <uni-icons type="phone" size="16" color="#007AFF"></uni-icons>
              </button>
            </view>
          </view>
          <view class="info-row" v-if="bookingData.customer_email">
            <text class="info-label">邮箱地址</text>
            <text class="info-value">{{ bookingData.customer_email }}</text>
          </view>
        </view>
      </uni-card>

      <!-- 费用信息 -->
      <uni-card title="费用信息" :is-shadow="true">
        <view class="info-section">
          <view class="info-row">
            <text class="info-label">小时价格</text>
            <text class="info-value">¥{{ bookingData.hour_price || 0 }}/时</text>
          </view>
          <view class="info-row">
            <text class="info-label">使用时长</text>
            <text class="info-value">{{ Math.ceil((bookingData.duration || 0) / 60) }}小时</text>
          </view>
          <view class="info-row">
            <text class="info-label">总金额</text>
            <text class="info-value price">¥{{ bookingData.total_amount || 0 }}</text>
          </view>
          <view class="info-row" v-if="bookingData.deposit_amount">
            <text class="info-label">押金</text>
            <text class="info-value">¥{{ bookingData.deposit_amount }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">支付状态</text>
            <uni-tag 
              :text="getPaymentStatusText(bookingData.payment_status || 1)" 
              :type="getPaymentStatusType(bookingData.payment_status || 1)" 
              size="small"
            />
          </view>
          <view class="info-row" v-if="bookingData.payment_method">
            <text class="info-label">支付方式</text>
            <text class="info-value">{{ bookingData.payment_method }}</text>
          </view>
        </view>
      </uni-card>

      <!-- 特殊要求 -->
      <uni-card title="特殊要求" :is-shadow="true" v-if="bookingData.special_requirements">
        <view class="requirements-content">
          <text class="requirements-text">{{ bookingData.special_requirements }}</text>
        </view>
      </uni-card>

      <!-- 备注信息 -->
      <uni-card title="备注信息" :is-shadow="true" v-if="bookingData.notes">
        <view class="notes-content">
          <text class="notes-text">{{ bookingData.notes }}</text>
        </view>
      </uni-card>

      <!-- 操作记录 -->
      <uni-card title="操作记录" :is-shadow="true" v-if="operationLogs.length > 0">
        <view class="logs-section">
          <view 
            v-for="(log, index) in operationLogs" 
            :key="index"
            class="log-item"
          >
            <view class="log-time">{{ formatDateTime(log.created_at) }}</view>
            <view class="log-content">{{ log.content }}</view>
            <view class="log-operator" v-if="log.operator">操作人：{{ log.operator }}</view>
          </view>
        </view>
      </uni-card>

      <!-- 创建时间 -->
      <view class="create-info">
        <text class="create-text">创建时间：{{ formatDateTime(bookingData.created_at || '') }}</text>
        <text class="update-text">更新时间：{{ formatDateTime(bookingData.updated_at || '') }}</text>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions safe-area-inset-bottom" v-if="bookingData.id">
      <button class="edit-btn" @click="navigateToEdit">编辑预订</button>
      <button class="more-btn" @click="showMoreActions">更多操作</button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchBookingDetail, updateBookingStatus } from '@/api/booking';
import type { Booking } from '@/types/booking';

const bookingData = ref<Partial<Booking>>({});
const operationLogs = ref<any[]>([]);
const loading = ref(false);
const bookingId = ref<number | null>(null);

// 获取预订详情
const getBookingDetail = async () => {
  if (!bookingId.value) return;
  
  loading.value = true;
  try {
    const res = await fetchBookingDetail(bookingId.value);
    bookingData.value = res;
    
    // 模拟操作记录
    operationLogs.value = [
      {
        created_at: res.created_at,
        content: '预订创建',
        operator: '系统',
      },
    ];
    
    if (res.status >= 2) {
      operationLogs.value.push({
        created_at: res.updated_at,
        content: '预订已确认',
        operator: '管理员',
      });
    }
    
    if (res.status >= 3) {
      operationLogs.value.push({
        created_at: res.updated_at,
        content: '开始使用',
        operator: '管理员',
      });
    }
    
    if (res.status >= 4) {
      operationLogs.value.push({
        created_at: res.updated_at,
        content: '使用结束',
        operator: '管理员',
      });
    }
  } catch (error) {
    console.error('获取预订详情失败:', error);
    uni.showToast({ title: '获取预订详情失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
  const weekDay = weekDays[date.getDay()];
  return `${year}-${month}-${day} 周${weekDay}`;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    1: '待确认',
    2: '已确认',
    3: '进行中',
    4: '已完成',
    5: '已取消',
    6: '已退款',
  };
  return statusMap[status] || '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'default',
    5: 'error',
    6: 'info',
  };
  return typeMap[status] || 'default';
};

// 获取预订类型文本
const getBookingTypeText = (type: number) => {
  const typeMap: { [key: number]: string } = {
    1: '小时预订',
    2: '全天预订',
  };
  return typeMap[type] || '未知';
};

// 获取支付状态文本
const getPaymentStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    1: '未支付',
    2: '已支付',
    3: '部分退款',
    4: '全额退款',
  };
  return statusMap[status] || '未知';
};

// 获取支付状态类型
const getPaymentStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'error',
    2: 'success',
    3: 'warning',
    4: 'info',
  };
  return typeMap[status] || 'default';
};

// 确认预订
const confirmBooking = async () => {
  if (!bookingData.value.id) return;
  try {
    await updateBookingStatus(bookingData.value.id, 2);
    uni.showToast({ title: '预订已确认' });
    getBookingDetail();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 取消预订
const cancelBooking = () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消这个预订吗？',
    success: async (res) => {
      if (res.confirm && bookingData.value.id) {
        try {
          await updateBookingStatus(bookingData.value.id, 5);
          uni.showToast({ title: '预订已取消' });
          getBookingDetail();
        } catch (error) {
          uni.showToast({ title: '操作失败', icon: 'none' });
        }
      }
    }
  });
};

// 开始使用
const startBooking = async () => {
  if (!bookingData.value.id) return;
  try {
    await updateBookingStatus(bookingData.value.id, 3);
    uni.showToast({ title: '已开始使用' });
    getBookingDetail();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 结束使用
const finishBooking = async () => {
  if (!bookingData.value.id) return;
  try {
    await updateBookingStatus(bookingData.value.id, 4);
    uni.showToast({ title: '使用已结束' });
    getBookingDetail();
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 拨打电话
const makeCall = () => {
  if (!bookingData.value.customer_phone) return;
  uni.makePhoneCall({
    phoneNumber: bookingData.value.customer_phone,
    fail: (err) => {
      console.error('拨打电话失败:', err);
    }
  });
};

// 导航到编辑页面
const navigateToEdit = () => {
  uni.navigateTo({ 
    url: `/pages/bookings/edit?id=${bookingId.value}` 
  });
};

// 显示更多操作
const showMoreActions = () => {
  const actions = ['复制预订信息', '发送短信通知', '导出预订单'];
  
  if (bookingData.value.status === 2 || bookingData.value.status === 3) {
    actions.push('申请退款');
  }
  
  uni.showActionSheet({
    itemList: actions,
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          copyBookingInfo();
          break;
        case 1:
          sendSmsNotification();
          break;
        case 2:
          exportBookingOrder();
          break;
        case 3:
          if (actions[3] === '申请退款') {
            applyRefund();
          }
          break;
      }
    }
  });
};

// 复制预订信息
const copyBookingInfo = () => {
  const info = `预订信息：
场地：${bookingData.value.venue_name || ''}
客户：${bookingData.value.customer_name || ''}
电话：${bookingData.value.customer_phone || ''}
日期：${formatDate(bookingData.value.booking_date || '')}
时间：${bookingData.value.start_time} - ${bookingData.value.end_time}
金额：¥${bookingData.value.total_amount || 0}
状态：${getStatusText(bookingData.value.status || 1)}`;

  uni.setClipboardData({
    data: info,
    success: () => {
      uni.showToast({ title: '已复制到剪贴板' });
    }
  });
};

// 发送短信通知
const sendSmsNotification = () => {
  uni.showToast({ title: '短信通知功能开发中', icon: 'none' });
};

// 导出预订单
const exportBookingOrder = () => {
  uni.showToast({ title: '导出功能开发中', icon: 'none' });
};

// 申请退款
const applyRefund = () => {
  uni.showModal({
    title: '申请退款',
    content: '确定要为此预订申请退款吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({ title: '退款申请已提交', icon: 'none' });
      }
    }
  });
};

onLoad((options: any) => {
  if (options.id) {
    bookingId.value = Number(options.id);
    uni.setNavigationBarTitle({ title: '预订详情' });
    getBookingDetail();
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.detail-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.status-card {
  background-color: #fff;
  margin: 10px;
  border-radius: var(--border-radius);
  padding: 15px;
  box-shadow: var(--shadow);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.booking-id {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.status-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  min-width: 80px;
  
  &.confirm {
    background-color: var(--primary-color);
    color: #fff;
  }
  
  &.cancel {
    background-color: #ff4757;
    color: #fff;
  }
  
  &.start {
    background-color: #2ed573;
    color: #fff;
  }
  
  &.finish {
    background-color: #ffa502;
    color: #fff;
  }
}

.uni-card {
  margin: 10px !important;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 24px;
}

.info-label {
  font-size: 14px;
  color: var(--text-color-secondary);
  flex-shrink: 0;
  width: 80px;
}

.info-value {
  font-size: 14px;
  color: var(--text-color);
  flex: 1;
  text-align: right;
  
  &.price {
    font-size: 16px;
    font-weight: bold;
    color: var(--primary-color);
  }
}

.info-value-with-action {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  justify-content: flex-end;
}

.call-btn {
  padding: 4px 8px;
  background-color: #f0f8ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.requirements-content, .notes-content {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.requirements-text, .notes-text {
  font-size: 14px;
  color: var(--text-color);
  line-height: 1.5;
}

.logs-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.log-item {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 3px solid var(--primary-color);
}

.log-time {
  font-size: 12px;
  color: var(--text-color-secondary);
  margin-bottom: 4px;
}

.log-content {
  font-size: 14px;
  color: var(--text-color);
  margin-bottom: 4px;
}

.log-operator {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.create-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 15px;
  background-color: #f8f9fa;
  margin: 10px;
  border-radius: var(--border-radius);
}

.create-text, .update-text {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  display: flex;
  gap: 10px;
}

.edit-btn, .more-btn {
  flex: 1;
  height: 44px;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.edit-btn {
  background-color: var(--primary-color);
  color: #fff;
}

.more-btn {
  background-color: #f5f5f5;
  color: #666;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>